import { useMemberStore } from "@/store/module/member";

/**
 * 页面跳转
 * @param url 目标页面的URL
 * @param needLogin 目标页面是否需要登录
 * @returns
 */
export const goPage = (url:string, needLogin?:boolean) => {
  const memberStore = useMemberStore();
  if (!memberStore.userInfo && needLogin) {
    toLogin();
    return;
  }
  uni.navigateTo({
        url: url,
        fail: (err) => {
            if (err.errMsg == "navigateTo:fail can not navigateTo a tabbar page") {
                uni.switchTab({ url: url });
            }
            if (err.errMsg == "navigateTo:fail:can not navigate to a tab bar page") {
                uni.switchTab({ url: url });
            }
        },
    });
}


/**
 * 跳转登陆页
 * @returns
 */
export const toLogin = () => {
  uni.navigateTo({
    url: "/pages/user/login",
  });
}


/**
 * 返回上一页
 * @param delay 延迟时间（毫秒）
 */
export const back = (delay: number = 0) => {
    const pages = getCurrentPages();
    if (pages.length > 1) {
        setTimeout(() => {
            uni.navigateBack({ delta: 1 });
        }, delay);
    } else {
        uni.reLaunch({ url: "/pages/index/index" });
    }
};


/**
 * 获取单个节点的信息
 * @param elSelectorQuery 查询节点信息的对象
 * @param nodeId 节点ID
 * @returns
 */
export const getNodeInfo = (elSelectorQuery: UniApp.SelectorQuery, nodeId: string): Promise<UniApp.NodeInfo> => {
    return new Promise((resolve, reject) => {
        elSelectorQuery
            .select(nodeId)
            .boundingClientRect((res: UniApp.NodeInfo | UniApp.NodeInfo[]) => {
                if (!Array.isArray(res)) {
                    const noteInfo: UniApp.NodeInfo = res;
                    resolve(noteInfo);
                } else {
                    reject(false);
                }
            })
            .exec();
    });
};


/**
 * 拨打电话
 * @param {*} mobile 电话
 */
export const baseCall = (mobile: number | string) => {
    mobile = mobile + "";
    if (mobile) {
        // #ifdef APP-PLUS
        plus.device.dial(mobile, false);
        // #endif
        // #ifndef APP-PLUS
        uni.makePhoneCall({
            phoneNumber: mobile, //仅为示例
        });
        // #endif
    } else {
        uni.showToast({
            title: "电话号码为空",
            icon: "none",
        });
    }
};
